package qiniufile

import (
	"context"
	// "fmt"
	"net/http"
	"strings"

	"mall/service/attachment/rpc/attachmentclient"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/utils/pointy"

	// "github.com/qiniu/go-sdk/v7/auth"
	// "github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type PfopCallbackLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	r      *http.Request
}

func NewPfopCallbackLogic(r *http.Request, svcCtx *svc.ServiceContext) *PfopCallbackLogic {
	return &PfopCallbackLogic{
		Logger: logx.WithContext(r.Context()),
		ctx:    r.Context(),
		svcCtx: svcCtx,
		r:      r,
	}
}

func (l *PfopCallbackLogic) PfopCallback(req *types.PfopCallbackReq) (resp *types.PfopCallbackResp, err error) {
	// logrus.Info(fmt.Sprintf("PfopCallback PfopCallbackReq: %+v", req))
	// {Id:z2.01z201cxgbhf3o5fv700mv2nrn000l9y Pipeline:1382448083.scentrobe_private Code:0 Desc:The fop was completed successfully ReqId:KaAAAABbCIy8550X InputBucket:dujiaoxiu InputKey:uploads/attachment/2023/07/cdc095e9f74136f993330f0885f16128.jpg Items:[0xc0012bb780]}

	returnCode := "failed"

	if req.Code == 0 && len(req.Id) > 0 && len(req.InputKey) > 0 && len(req.Items) > 0 &&
		strings.HasPrefix(req.InputBucket, l.svcCtx.Config.QiniuConf.Bucket) {
		// Todo:  处理验证不过的问题
		// at := auth.New(l.svcCtx.Config.QiniuConf.AccessKey, l.svcCtx.Config.QiniuConf.SecretKey)
		// if ok, err := at.VerifyCallback(l.r); ok {
		var keys []string
		for _, v := range req.Items {
			if len(v.Key) > 0 {
				keys = append(keys, v.Key)
			}
			if len(v.Keys) > 0 {
				keys = append(keys, v.Keys...)
			}
		}
		// logrus.Info(fmt.Sprintf("PfopCallback keys: %+v", keys))
		_, err = l.svcCtx.AttachmentRpc.QiniuCallback(l.ctx, &attachmentclient.RecordInfo{
			Id:       pointy.GetPointer(req.Id),
			Key:      pointy.GetPointer(req.InputKey),
			Bucket:   pointy.GetPointer(req.InputBucket),
			Diagnose: pointy.GetPointer(uint32(32)),
			Style:    pointy.GetPointer(strings.Join(keys, ",")),
		})
		if err != nil {
			logx.Errorw("PfopCallback err", logx.Field("detail", err.Error()))
		} else {
			returnCode = "success"
		}
		// } else {
		// 	logrus.Info(fmt.Sprintf("PfopCallback VerifyCallback err: %+v", err))
		// 	EOF
		// }
	}

	return &types.PfopCallbackResp{
		ReturnCode: returnCode,
	}, err
}
